package cn.wzvtc.demo.service;

import cn.wzvtc.demo.common.constant.CommonStatus;
import cn.wzvtc.demo.common.exception.CommonException;
import cn.wzvtc.demo.model.entity.UserFormEntity;
import com.mongodb.BasicDBObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;


/**
 * @description: 用户表单服务类
 * @author: Rex
 * @create: 2021-07-10 19:08
 */
@Service
public class UserFormService {
  @Autowired
  private MongoTemplate mongoTemplate;

  /**
   * 提交表单
   * @param userFormEntity 用户填写的表单
   * @return 保存结果
   */
  public UserFormEntity save(UserFormEntity userFormEntity) {
    return mongoTemplate.insert(userFormEntity);
  }


  /**
   * 根据id删除整个表t
   * @param id 表单编号
   */
  public void deleteById(String id){
    Query query = Query.query(Criteria.where("id").is(id));
    DeleteResult res = mongoTemplate.remove(query, UserFormEntity.class);
    if (res.getDeletedCount() == 0){
      throw new CommonException(CommonStatus.DELETE_ERROR);
    }
  }

  /**
   * 根据表单编号和组件编号删除组件
   * @param id 表单编号
   * @param componentId 组件编号
   */
  public void deleteByIdAndComponentId(String id, String componentId) {
    Update update = new Update();
    update.pull("components",new BasicDBObject("id",componentId));
    Query query = Query.query(Criteria.where("id").is(id));
    UpdateResult res = mongoTemplate.updateFirst(query, update, UserFormEntity.class);
    if(res.getModifiedCount() == 0){
      throw new CommonException(CommonStatus.DELETE_ERROR);
    }
  }


  /**
   * 根据ID查找数据
   * @param id 用户用户表单编号
   * @return 用户填写的表单
   */
  public UserFormEntity findById(String id) {
    Query query = new Query(Criteria.where("id").is(id));
    return mongoTemplate.findOne(query, UserFormEntity.class);
  }

  /**
   * 根据ID更新数据
   * @param UserFormEntity 待更新表单
   */
  public void update(UserFormEntity UserFormEntity) {
    Query query = new Query(Criteria.where("id").is(UserFormEntity.getId()));
    Update update = new Update();
    update.set("components", UserFormEntity.getComponents());
    //更新查询返回的结果集的第一条数据
    UpdateResult result = mongoTemplate.updateFirst(query, update, UserFormEntity.class);
  }
}
